#!/bin/sh

csid=$1
oracleHome=$2
ouser=$3

if [ "$#" -ne 3 ]; then
 echo "This script needs 3 input parameter"
 echo "usage: OracleAppTeardown.sh <New database sid name> <Oracle Home path> <Oracle User>"
 echo " For example: OracleAppTeardown.sh clonedb /home/oracle/app/oracle/product/11.2.0/dbhome_1 oracle"
exit 1
fi

scriptsRoot=${LB_ROOT}
if [ -z "$scriptsRoot" ];then
    echo "missing env LB_ROOT"
    exit 1
fi

. ${scriptsRoot}/oracle/oracleclone/OracleAppMountComFunc.sh

CSID=`echo $csid | tr [a-z] [A-Z]`
echo $CSID
echo $csid

function cleanup
{
   path=$1
   if [ -e $path ]; then
      echo "removing $path and all its contents" 
      find $path -delete      
   fi
}


# correctly set the ORACLE_BASE AND ORACLE_HOME  for your environment
export ORACLE_HOME=$oracleHome
export ORACLE_SID=$csid
export PATH=$ORACLE_HOME/bin:$PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib
export LD_LIBRARY_PATH

if [ ! -d $ORACLE_HOME ]; then
   echo "missing ORACLE_HOME "
   exit 1
fi

nsid=`ps -ef | grep pmon | grep -i $csid | awk '{ print $NF }' | cut -f3 -d"_"`
if [ ! -z $nsid ] && [ "$nsid" = "$csid" ]; then
su $ouser -c "$ORACLE_HOME/bin/sqlplus -s / as sysdba << EOF
set heading off
set feedback off
shutdown immediate;
exit;
EOF
"
   if [ $? != 0 ]; then
      # shutdown failed, exit without cleanup ora files
      echo "shutdown failed for $csid"
      exit 1
   fi
fi

if [ -z "$isrestore" ] || [ "$isrestore" != "true" ]; then
#removing database cluster entries
#su $ouser -c "$ORACLE_HOME/bin/srvctl remove database -d $csid -f &> /dev/null"

if [ "$notnsupdate" != "true" ]; then
# cleanup tns entry
${scriptsRoot}/oracle/oracleclone/cleanupTNSNames.sh $csid $ORACLE_HOME 6 $tnsadmindir
fi

setdbf=${scriptsRoot}/oracle/oracleclone/setdb_$csid

echo "cleanup init$csid.ora"
echo "cleanup init$CSID.ora"
rm -f $ORACLE_HOME/dbs/init$csid.ora
rm -f $ORACLE_HOME/dbs/init$CSID.ora
rm -f $ORACLE_HOME/dbs/spfile$csid.ora
rm -f $ORACLE_HOME/dbs/spfile$CSID.ora
rm -f $ORACLE_HOME/dbs/orapw$csid
rm -f $ORACLE_HOME/dbs/orapw$CSID
#rm -f $ORACLE_BASE/admin/*$csid*
rm $setdbf
fi

echo "done rewind"
exit 0
